package com.platform.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.platform.dao.*;
import com.platform.entity.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.platform.cache.J2CacheUtils;
import com.platform.util.CommonUtil;


@Service
public class ApiOrderService {
    @Autowired
    private ApiOrderMapper orderDao;
    @Autowired
    private ApiAddressMapper apiAddressMapper;
    @Autowired
    private ApiCartMapper apiCartMapper;
    @Autowired
    private ApiCouponMapper apiCouponMapper;
    @Autowired
    private ApiOrderMapper apiOrderMapper;
    @Autowired
    private ApiOrderGoodsMapper apiOrderGoodsMapper;
    @Autowired
    private ApiProductService productService;
    @Autowired
    private ApiGoodsService goodsService;


    public OrderVo queryObject(Integer id) {
        return orderDao.queryObject(id);
    }


    public List<OrderVo> queryList(Map<String, Object> map) {
        return orderDao.queryList(map);
    }


    public int queryTotal(Map<String, Object> map) {
        return orderDao.queryTotal(map);
    }


    public void save(OrderVo order) {
        orderDao.save(order);
    }


    public int update(OrderVo order) {
        return orderDao.update(order);
    }


    public void delete(Integer id) {
        orderDao.delete(id);
    }


    public void deleteBatch(Integer[] ids) {
        orderDao.deleteBatch(ids);
    }


    @Transactional
    public Map<String, Object> submit(JSONObject jsonParam, UserVo loginUser) {
        Map<String, Object> resultObj = new HashMap<String, Object>();

        Integer couponId = jsonParam.getInteger("couponId");
        String type = jsonParam.getString("type");
        String postscript = jsonParam.getString("postscript");
//        AddressVo addressVo = jsonParam.getObject("checkedAddress",AddressVo.class);
        AddressVo addressVo = apiAddressMapper.queryObject(jsonParam.getInteger("addressId"));
        //中大团队拓展
        Integer deptId = jsonParam.getInteger("deptId");
        Integer userGrade = jsonParam.getInteger("userGrade");

        Integer freightPrice = 0;

        // * 获取要购买的商品
        List<CartVo> checkedGoodsList = new ArrayList<>();
        BigDecimal goodsTotalPrice = new BigDecimal(0.00);
        if (type.equals("cart")) {
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("user_id", loginUser.getUserId());
            param.put("session_id", 1);
            param.put("checked", 1);
            List<CartVo> checkedGoodsListTemp = apiCartMapper.queryList(param);
            //中大团队扩展，数据过滤，只获取当前商家商品
            for (CartVo cartVo : checkedGoodsListTemp) {
                Integer goodsId = cartVo.getGoods_id();
                param = new HashMap();
                param.put("root_dept_id", deptId);
                param.put("id", goodsId);
                int total = goodsService.queryTotalByDeptId(param);
                if (total != 0) checkedGoodsList.add(cartVo);
            }
        }
        else {
            BuyGoodsVo goodsVo = (BuyGoodsVo) J2CacheUtils.get(J2CacheUtils.SHOP_CACHE_NAME, "goods" + loginUser.getUserId());
            ProductVo productInfo = productService.queryObject(goodsVo.getProductId());
            GoodsVo goodsInfo=goodsService.queryObject(goodsVo.getGoodsId());
            //计算订单的费用
            //商品总价
            //中大团队拓展,计算单价
            int number=goodsVo.getNumber();
            double realSingleGoodsPrice;
            if(goodsInfo.getPrice_type().equals("1")){
                if(userGrade == 0)
                    realSingleGoodsPrice=Double.valueOf(goodsInfo.getCounter_price().toString());
                else if (userGrade== 1)
                    realSingleGoodsPrice= goodsInfo.getCounter_sec_price();

                else
                    realSingleGoodsPrice=goodsInfo.getCounter_thi_price();

            }
            else if (goodsInfo.getPrice_type().equals("0")) {
                if (userGrade ==  1) {
                    if (number < goodsInfo.getFirst_num())
                        realSingleGoodsPrice=goodsInfo.getClient_price();
                    else if (number >= goodsInfo.getFirst_num() && number < goodsInfo.getSecond_num())
                        realSingleGoodsPrice=goodsInfo.getClient_price()*goodsInfo.getFirst_discount();

                    else
                        realSingleGoodsPrice=goodsInfo.getClient_price()*goodsInfo.getSecond_discount();
                }
                else{
                    if (number < goodsInfo.getFirst_num())
                        realSingleGoodsPrice=goodsInfo.getVip_client_price();
                    else if (number >= goodsInfo.getFirst_num() && number < goodsInfo.getSecond_num())
                        realSingleGoodsPrice=goodsInfo.getVip_client_price()*goodsInfo.getFirst_discount();
                    else
                        realSingleGoodsPrice=goodsInfo.getVip_client_price()*goodsInfo.getSecond_discount();
                }
            }
            else{
                if (userGrade ==  1)
                    realSingleGoodsPrice=goodsInfo.getSingle_share_cost()+ goodsInfo.getSingle_make_cost() + goodsInfo.getSingle_order_cost()/number + goodsInfo.getSingle_profit_cost()* goodsInfo.getFirst_discount();
                else
                    realSingleGoodsPrice = goodsInfo.getSingle_share_cost() + goodsInfo.getSingle_make_cost() + goodsInfo.getSingle_order_cost() / number + goodsInfo.getSingle_profit_cost() * goodsInfo.getSecond_discount();
            }
            BigDecimal onePrice=BigDecimal.valueOf(realSingleGoodsPrice);
            goodsTotalPrice = onePrice.multiply(new BigDecimal(goodsVo.getNumber()));

            CartVo cartVo = new CartVo();
            BeanUtils.copyProperties(productInfo, cartVo);
            cartVo.setNumber(goodsVo.getNumber());
            cartVo.setProduct_id(goodsVo.getProductId());
            cartVo.setRetail_price(onePrice);
            checkedGoodsList.add(cartVo);
        }

        //获取订单使用的优惠券
        BigDecimal couponPrice = new BigDecimal(0.00);
        CouponVo couponVo = null;
        if (couponId != null && couponId != 0) {
            couponVo = apiCouponMapper.getUserCoupon(couponId);
            if (couponVo != null && couponVo.getCoupon_status() == 1) {
                couponPrice = couponVo.getType_money();
            }
        }

        OrderVo orderInfo = new OrderVo();
        apiOrderMapper.save(orderInfo);
        if (null == orderInfo.getId()) {
            resultObj.put("errno", 1);
            resultObj.put("errmsg", "订单提交失败");
            return resultObj;
        }

        BigDecimal orderPrice = BigDecimal.valueOf(0);
        BigDecimal goodsPrice = BigDecimal.valueOf(0);
        BigDecimal actPrice;
        for (CartVo cartItem : checkedGoodsList) {
            if (type.equals("cart"))
                goodsTotalPrice = goodsTotalPrice.add(cartItem.getRetail_price().multiply(new BigDecimal(cartItem.getNumber())));

            //订单价格计算
            BigDecimal orderTotalPrice = goodsTotalPrice; //订单的总价

            BigDecimal actualPrice = orderTotalPrice.subtract(couponPrice);  //减去其它支付的金额后，要实际支付的金额

            Long currentTime = System.currentTimeMillis() / 1000;

            //中大团队拓展
            BigDecimal number = new BigDecimal(cartItem.getNumber());
            orderPrice = orderPrice.add(cartItem.getRetail_price().multiply(number));
            goodsPrice = goodsPrice.add(cartItem.getRetail_price());
            //

            //统计商品总价
            OrderGoodsVo orderGoodsVo = new OrderGoodsVo();
            orderGoodsVo.setOrder_id(orderInfo.getId());
            orderGoodsVo.setGoods_id(cartItem.getGoods_id());
            //中大团队扩展,算拼单量
            GoodsVo goodsVo = goodsService.queryObject(cartItem.getGoods_id());
            if (goodsVo.getSale_type().equals("p")) {
                Integer orderNum = cartItem.getNumber();
                Integer goodsCurrNum = goodsVo.getCollage_curr_num();
                goodsVo.setCollage_curr_num(orderNum + goodsCurrNum);
                goodsService.updateCollageNum(goodsVo);
            }
            if (goodsVo.getSale_type().equals("x")) {
                //中大团队扩展，订单提交减库存
                ProductVo productVo = productService.queryObject(cartItem.getProduct_id());
                Integer productNum = productVo.getGoods_number();
                productVo.setGoods_number(productNum - cartItem.getNumber());
                productService.update(productVo);
            }

            orderGoodsVo.setGoods_sn(cartItem.getGoods_sn());
            orderGoodsVo.setProduct_id(cartItem.getProduct_id());
            orderGoodsVo.setGoods_name(cartItem.getGoods_name());
            orderGoodsVo.setList_pic_url(cartItem.getList_pic_url());
            orderGoodsVo.setMarket_price(cartItem.getMarket_price() == null ? BigDecimal.valueOf(0) : cartItem.getMarket_price());
            orderGoodsVo.setRetail_price(cartItem.getRetail_price());
            orderGoodsVo.setNumber(cartItem.getNumber());
            orderGoodsVo.setGoods_specifition_name_value(cartItem.getGoods_specifition_name_value());
            orderGoodsVo.setGoods_specifition_ids(cartItem.getGoods_specifition_ids());

            apiOrderGoodsMapper.save(orderGoodsVo);

            //清空已购买的商品
            apiCartMapper.delete(cartItem.getId());
        }

        orderInfo.setRoot_dept_id(deptId);
        orderInfo.setOrder_sn(CommonUtil.generateOrderNumber());
        orderInfo.setUser_id(loginUser.getUserId());
        //收货地址和运费
        orderInfo.setConsignee(addressVo.getUserName());
        orderInfo.setMobile(addressVo.getTelNumber());
        orderInfo.setCountry(addressVo.getNationalCode());
        orderInfo.setProvince(addressVo.getProvinceName());
        orderInfo.setCity(addressVo.getCityName());
        orderInfo.setDistrict(addressVo.getCountyName());
        orderInfo.setAddress(addressVo.getDetailInfo());
        //
        orderInfo.setFreight_price(freightPrice);
        //留言
        orderInfo.setPostscript(postscript);
        //使用的优惠券
        orderInfo.setCoupon_id(couponId);
        orderInfo.setCoupon_price(couponPrice);
        orderInfo.setAdd_time(new Date());
        orderInfo.setGoods_price(goodsPrice);
        orderInfo.setOrder_price(orderPrice);
        actPrice = orderPrice.subtract(couponPrice);
        orderInfo.setActual_price(actPrice);
        // 待付款
        orderInfo.setOrder_status(0);
        orderInfo.setShipping_status(0);
        orderInfo.setPay_status(0);
        orderInfo.setShipping_id(0);
        orderInfo.setShipping_fee(new BigDecimal(0));
        orderInfo.setIntegral(0);
        orderInfo.setIntegral_money(new BigDecimal(0));
        if (type.equals("cart")) {
            orderInfo.setOrder_type("1");
        } else {
            orderInfo.setOrder_type("4");
        }

        //开启事务，插入订单信息
        int re = apiOrderMapper.update(orderInfo);
        if (re == 0) {
            resultObj.put("errno", 1);
            resultObj.put("errmsg", "订单提交失败");
            return resultObj;
        }

        resultObj.put("errno", 0);
        resultObj.put("errmsg", "订单提交成功");
        //
        Map<String, OrderVo> orderInfoMap = new HashMap<String, OrderVo>();
        orderInfoMap.put("orderInfo", orderInfo);
        //
        resultObj.put("data", orderInfoMap);
        // 优惠券标记已用
        if (couponVo != null && couponVo.getCoupon_status() == 1) {
            couponVo.setCoupon_status(2);
            apiCouponMapper.updateUserCoupon(couponVo);
        }

        return resultObj;
    }

}
